#include "bhxjglpointer1.h"

BHXJGLPointer1::BHXJGLPointer1()
{

}

BHXJGLPointer1::~BHXJGLPointer1()
{
    if(this->gl!=nullptr)
    {
        gl->glDeleteVertexArrays(1,&VAO);
        gl->glInvalidateBufferData(EBO);
        gl->glInvalidateBufferData(VBO);
    }
}

void BHXJGLPointer1::Init(QOpenGLFunctions_4_3_Core *g, BHXJGLShader *s)
{
    this->gl=g;
    this->shader=s;


    float vertices[] = {
        //---- 位置 ----     - 纹理坐标 -
        0.0f,  1.0f,0,       0.5f, 1.0f,
        0.1f, 0.0f,0,       0.6f, 0.5f,
        0.0f, -1.0f,0,      0.5f, 0.0f,
        -0.1f,  0.0f,0,      0.4f, 0.5f,
        0.0f,  0.0f,0.05f,      0.5f, 0.5f
    };
    unsigned int indices[] = {
        0, 1, 4,
        1, 2, 4 ,
        2, 3, 4 ,
        3, 0, 4
    };
    gl->glGenVertexArrays(1,&VAO);
    gl->glGenBuffers(1,&VBO);
    gl->glGenBuffers(1,&EBO);

    gl->glBindVertexArray(VAO);

    gl->glBindBuffer(GL_ARRAY_BUFFER,VBO);
    gl->glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);

    gl->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO);
    gl->glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_STATIC_DRAW);

    gl->glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,5*sizeof(float),nullptr);
    gl->glEnableVertexAttribArray(0);

    gl->glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,5*sizeof(float),reinterpret_cast<void*>(3*sizeof(float)));
    gl->glEnableVertexAttribArray(1);


    gl->glBindVertexArray(0);
    gl->glBindBuffer(GL_ARRAY_BUFFER, 0);
    gl->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
}

void BHXJGLPointer1::Paint(const BHXJGLPaintParam& p)
{
    if(this->gl==nullptr||this->shader==nullptr)
        return;
    this->shader->use();
    this->shader->setMat4("model",p.Model());
    this->shader->setMat4("view",p.View());
    this->shader->setMat4("projection",p.Projection());
    this->gl->glBindVertexArray(VAO);
    this->shader->setVec4("Color",glm::vec4(_Color0.red()/255.f,_Color0.green()/255.f,_Color0.blue()/255.f,1));
    this->gl->glDrawElements(GL_TRIANGLES,3,GL_UNSIGNED_INT,reinterpret_cast<void*>(0));

    this->shader->setVec4("Color",glm::vec4(_Color1.red()/255.f,_Color1.green()/255.f,_Color1.blue()/255.f,1));
    this->gl->glDrawElements(GL_TRIANGLES,3,GL_UNSIGNED_INT,reinterpret_cast<void*>(3*sizeof (unsigned int)));

    this->shader->setVec4("Color",glm::vec4(_Color2.red()/255.f,_Color2.green()/255.f,_Color2.blue()/255.f,1));
    this->gl->glDrawElements(GL_TRIANGLES,3,GL_UNSIGNED_INT,reinterpret_cast<void*>(6*sizeof (unsigned int)));

    this->shader->setVec4("Color",glm::vec4(_Color3.red()/255.f,_Color3.green()/255.f,_Color3.blue()/255.f,1));
    this->gl->glDrawElements(GL_TRIANGLES,3,GL_UNSIGNED_INT,reinterpret_cast<void*>(9*sizeof (unsigned int)));
    this->gl->glBindVertexArray(0);

}

